<?php

class Storefront_CartController extends Zend_Controller_Action
{
    
    /**
     * The cart model
     *
     * @var Storefront_Model_Cart
     */
    protected $_cartModel;
    
    /**
     * The catalog model
     *
     * @var Storefront_Model_Catalog
     */
    protected $_catalogModel;

    public function init()
    {
        
        $this->_cartModel = new Storefront_Model_Cart;
        $this->_catalogModel = new Storefront_Model_Catalog;
        
    }

    /**
     * Add cart items 
     * and redirect to the address specified in 'returnto' parameter
     *
     * @return void
     */
    public function addAction()
    {
        
        $product = $this->_catalogModel->getProductById(
                $this->_getParam('productId')
            );
        
        if (null === $product) {
            throw new SF_Exception('Product could not be add to the cart asit does not exist');
        }
        
        $this->_cartModel->addItem($product, $this->_getParam('qty'));
        
        $return = rtrim(
                $this->getRequest()->getBaseUrl(), '/'
            ) . $this->_getParam('returnto');
        
        $redirector = $this->getHelper('redirector');
        
        return $redirector->gotoUrl($return);
        
    }
    
    /**
     * Update cart items.
     * 'quantity' is a parameter array. Key is the productId 
     * and value is the new quantity.
     */
    public function updateAction()
    {
        
        foreach ($this->_getParam('quantity') as $id => $value) 
        {
            $product = $this->_catalogModel->getProductById($id);
            if (null !== $product) {
                $this->_cartModel->addItem($product, $value);
            }
        }
            
            $this->_cartModel->setShippingCost($this->_getParam('shipping'));

            
            return $this->_helper->redirector('view');
            
    }
    
    /**
     * View the cart content
     */
    public function viewAction()
    {
        
        $this->view->cartModel = $this->_cartModel;
        
    }


}

